package com.hl233.framework.nettyServer;

import com.hl233.framework.utils.DateUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author 张振强15065206763
 * @create 2024-09-07
 */
@Component
public class NettyHandler extends ChannelInboundHandlerAdapter {

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        InetSocketAddress insocket2 = (InetSocketAddress) ctx.channel().localAddress();
        System.out.println("客户端发起连接,端口：" + insocket2.getPort() + "；当前时间：" + DateUtil.now());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

//        String deviceName = ctx.channel().attr("deviceName").get();
//        if(deviceName!=null && ChannelHandlerContextMap.getInstance().containsKey(deviceName)){
//            ChannelHandlerContextMap.getInstance().remove(deviceName);
////            LogUtil.LOGI(NettyHandler.class.getName(),"客户端["+deviceName+"]断开连接");
//        }else{
////            LogUtil.LOGI(NettyHandler.class.getName(),"客户端["+ctx.channel().remoteAddress()+"]断开连接");
//        }

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        /**获取客户端的IP*/
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = insocket.getAddress().getHostAddress();

        InetSocketAddress insocket2 = (InetSocketAddress) ctx.channel().localAddress();
        System.out.println("本地端口" + insocket2.getPort());

        String sp = "$##";
        String write = "{\"code\":\"500\",\"message\":\"系统错误\"}";

        System.out.println("拿到客户端消息" + msg);

        ctx.writeAndFlush(write + sp);
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常");
        cause.printStackTrace();
        ctx.close();
    }

}
